package com.program.facesigninsystem.config;

import com.auth0.jwt.JWT;
import com.program.facesigninsystem.entity.ResponseModel;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Mapler
 */
public class ReqInterceptor extends HandlerInterceptorAdapter {
    private static Logger log = Logger.getLogger(ReqInterceptor.class.toString());
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //得到请求头
            if("OPTIONS".equals(request.getMethod())){
                //在拦截器中设置允许跨域
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Headers","*");
                response.setHeader("Access-Control-Allow-Methods","*");
                response.setHeader("Access-Control-Allow-Credentials","true");
                response.setHeader("Access-Control-Max-Age","3600");
                return true;
            }
            //获得token
            String authorization = request.getHeader("Authorization");
            String token = null;
            if(authorization != null) {
                token = authorization.substring(7);
            }
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            //如果token没有则返回
            if(token==null || token.length()==0){
                JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "无token，不允许访问！").toString());
                response.getWriter().append(jsonObject.toString()).flush();
                return false;
            }
            else {
                try{
                    Long currentTime = System.currentTimeMillis();
                    Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
                    Long expTime = JWT.decode(token).getClaim("exptime").asLong();
                    if(currentTime - generateTime > expTime) {
                        JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "token过期，请重新登录！").toString());
                        response.getWriter().append(jsonObject.toString()).flush();
                        return false;
                    }
                }catch (Exception e){
                    log.log(Level.SEVERE,"Error parsing date",e);
                    //验证失败
                    JSONObject jsonObject = JSONObject.fromObject(new ResponseModel(310, "token无效，不允许访问！").toString());
                    response.getWriter().append(jsonObject.toString()).flush();
                    return false;
                }
            }
            return super.preHandle(request, response, handler);
        }
}
